<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="workType"
        placeholder="工卡执行类型"
        clearable
        style="width: 190px"
        class="filter-item"
      >
        <el-option v-for="item in workTypes" :key="item" :label="item" :value="item"/>
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-upload2"
        @click="handleUpload"
      >移动工卡信息上传</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-delete"
        @click="handleDelete"
      >删除</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="workdatas"
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="选择" type="selection" width="40px" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <!-- {{ props.row[header] }} -->
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item v-for="header in workheader" :key="header" :label="header">
              <span v-if="header==='完工统计'">
                <span style="color: #409EFF">{{ props.row[header].work }}</span><span>{{ ' ' }}</span>
                <span style="color: #F56C6C">{{ props.row[header].check }}</span><span>{{ ' ' }}</span>
                <span style="color: #67C23A">{{ props.row[header].recheck }}</span><span>{{ ' ' }}</span>
              </span>
              <span v-else>{{ props.row[header] }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        v-for="header in fixedworkheader"
        :prop="header"
        :label="header"
        :key="header"
        align="center">
        <template slot-scope="scope">
          <router-link v-if="header==='ID'" :to="{ path: '/workcard/' + scope.row['workuid'], query: { 'workuid': scope.row['workuid']} }">
            <span class="link-type">{{ scope.row['ID'] }}</span>
          </router-link>
          <span v-else>{{ scope.row[header] }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { getWorklist, saveWorkcard, deleteWorkcard } from '@/utils/storage'
import { uploadPhoto, deleteAttachment, deletePhoto } from '@/utils/file'
import { uploadWorklist } from '@/api/workcard'
import { getAllAttachments, getAllPhotoObjects, getWorkcardCompleteStatistic, getWorkcardID } from '@/utils/workcard-util'

export default {
  data() {
    return {
      // 工卡的公共表头信息
      fixedworkheader: ['ID', '名称', '工卡类型', '编制', '机型号', '架机号'],
      // 根据选择的工卡类型，列出的工卡的列表头信息
      workheader: [],
      // 根据选择的工卡类型，所过滤出来的工卡子集列表，属性信息仅包含工卡属性
      workdatas: [],
      // 工卡类型
      workType: null,
      // 在某个工卡类型的子集中，选择下载的工卡
      selectedWorkcards: [],
      // 原始工卡，带有全部信息
      worklist: [],
      // 工卡类型
      workTypes: [
        '所有类型',
        '测试系统检查',
        '测试校准',
        'J1 机械安装',
        'J1 机械拆除',
        '机械生产准备',
        'D4 机械检查、试验及配合工作',
        '机械称重',
        'D3 电气安装',
        'D3 电气拆除',
        '电气检查、试验及配合工作',
        '电气盒体机柜类制作',
        '电气线缆地面制作',
        '电气线缆机上敷设',
        '电气线缆机上制作'
      ],
      loading: false
    }
  },
  watch: {
    workType(selectedValue) {
      this.getWorkCardDataAndHeaderByType(selectedValue)
    }
  },
  methods: {
    ...mapMutations([
      'ADD_WORKINSTRUCTION_ROUTERS'
    ]),
    getWorkCardDataAndHeaderByType(workType) {
      const that = this
      const finishstatistic = '完工统计'
      that.workdatas = []
      that.worklist = []
      that.workheader = ['ID', '名称', '工卡类型', '编制', '机型号', '架机号']
      getWorklist().then(
        worklist => {
          for (var i = 0; i < worklist.length; i++) {
            if (worklist[i].workcard.worktype === workType || workType === '所有类型') {
              const workcard = {}
              workcard.workuid = worklist[i].workcard.workuid
              worklist[i].workcard.workrelattrs.forEach(
                attr => {
                  // header
                  if (that.workheader.indexOf(attr.name) === -1) {
                    that.workheader.push(attr.name)
                  }
                  // 添加自定义的完工情况
                  if (that.workheader.indexOf(finishstatistic) === -1) {
                    that.workheader.push(finishstatistic)
                  }
                  // data
                  workcard[attr.name] = attr.value || ''
                  workcard[finishstatistic] = getWorkcardCompleteStatistic(worklist[i].workcard)
                }
              )
              workcard['工卡类型'] = worklist[i].workcard.worktype
              that.workdatas.push(workcard)
              that.worklist.push(worklist[i].workcard)
            }
          }
          console.log(that.workdatas)
        }
      )
    },
    handleUpload() {
      if (!this.$store.state.app.online) {
        this.$message.error('离线状态下不能上传工卡！')
        return
      }
      const that = this
      const tasks = []
      if (that.selectedWorkcards.length === 0) {
        that.$message.warning('请选择需要上传的工卡！')
        return
      }
      that.loading = true
      that.selectedWorkcards.forEach(
        selectedWorkcard => {
          that.worklist.forEach(
            workcard => {
              if (selectedWorkcard.workuid === workcard.workuid) {
                console.log('[upload]-[handleupload]-workcard.workuid: ' + workcard.workuid)

                // 获取工卡中所有照片信息
                const photoObjects = getAllPhotoObjects(workcard)
                const selectedPhotoObjects = []
                console.log('[upload]-[handleupload]-photoObjects: ' + JSON.stringify(photoObjects))
                // 上传照片
                const postPhotos = []
                photoObjects.forEach(
                  photoObject => {
                    if (!photoObject.uid) { // 如果uid不存在，说明photo还没上传上去，需要上传，否则就不用上传了
                      postPhotos.push(uploadPhoto(getWorkcardID(workcard), photoObject))
                      selectedPhotoObjects.push(photoObject)
                    }
                  }
                )
                const workcardUploading = Promise.all(postPhotos).then(
                  photoObjs => { // 上传成功
                    saveWorkcard(workcard) // 保存工卡
                    return workcard
                  },
                  error => {
                    console.log('[upload]-[handleupload]-error: ' + JSON.stringify(error))
                    selectedPhotoObjects.forEach( // 上传出错，再把以前的恢复原样
                      photoObject => {
                        photoObject.uid = ''
                      }
                    )
                    return '照片上传出错！'
                  }
                ).then(
                  () => {
                    // 上传工卡
                    console.log('[upload]-[handleupload]-workcard: ' + JSON.stringify(workcard))
                    return uploadWorklist([workcard]).then(
                      () => workcard
                    ).catch(err => {
                      console.log('[upload]-[handleupload]-uploadWorklist: ' + JSON.stringify(err))
                      return err
                    })
                  }
                ).catch(
                  err => {
                    console.log('[upload]-[handleupload]-workcard: ' + JSON.stringify(err))
                    return err
                  }
                )
                tasks.push(workcardUploading)
                // const workcardUploading = Promise.all(postPhotos).then(
                //   photoObjs => { // 上传成功
                //     saveWorkcard(workcard) // 保存工卡
                //     return workcard
                //   },
                //   error => {
                //     console.log('[upload]-[handleupload]-error: ' + JSON.stringify(error))
                //     selectedPhotoObjects.forEach( // 上传出错，再把以前的恢复原样
                //       photoObject => {
                //         photoObject.uid = ''
                //       }
                //     )
                //     return '照片上传出错！'
                //   }
                // ).then(
                //   () => {
                //     // 上传工卡
                //     console.log('[upload]-[handleupload]-workcard: ' + JSON.stringify(workcard))
                //     return uploadWorklist([workcard])
                //   }
                // ).then(
                //   resp => {
                //     console.log('[upload]-[handleupload]-success: ' + JSON.stringify(resp))
                //     console.log('[upload]-[handleupload]-success: ' + JSON.stringify('工卡保存成功!'))
                //     if (workcard.isfinished === 'True') {
                //       that.deleteAllWorkcardInformationWithConfirm(workcard, '已完工工卡上传成功，是否删除移动端: ' + that.getWorkcardID(workcard) + '?')
                //     } else {
                //       that.$message.success('工卡上传成功！')
                //     }
                //   }
                // ).catch(
                //   err => {
                //     console.log('error: ' + err)
                //     if (err.message === 'Network Error') {
                //       that.$message.error('网络错误，未连接到服务器！')
                //     } else if (err.response && err.response.data && err.response.data.message) {
                //       if (err.response.data.message.indexOf('工单结果提交失败: 工卡已经执行完成') !== -1) {
                //         that.deleteAllWorkcardInformationWithConfirm(workcard, '工单结果提交失败, 工卡已经执行完成: ' + that.getWorkcardID(workcard) + ',是否删除移动端该工卡?')
                //       } else {
                //         that.$message.error('工卡上传出错: ' + err)
                //       }
                //     } else {
                //       that.$message.error('工卡上传出错: ' + err)
                //     }
                //   }
                // )
              }
            }
          )
        }
      )
      Promise.all(tasks).then(
        workcards => {
          // console.log('[upload]-[handleupload]-success: ' + JSON.stringify(resp))
          console.log('[upload]-[handleupload]-success: ' + JSON.stringify('工卡保存成功!'))
          const finishedWorkcards = []
          workcards.forEach(
            workcard => {
              if (workcard.isfinished === 'True') {
                finishedWorkcards.push(workcard)
              }
            }
          )
          if (finishedWorkcards.length !== 0) {
            that.deleteAllWorkcardInformationWithConfirm(finishedWorkcards, '工卡上传成功，是否删除移动端已完工工卡[' + finishedWorkcards.map(v => v.workrelattrs.find(w => w.name === 'ID').value) + ']？')
          } else {
            that.$message.success('工卡上传成功！')
            that.loading = false
          }
        }
      ).catch(
        err => {
          console.log('error: ' + err)
          if (err.message === 'Network Error') {
            that.$message.error('网络错误，未连接到服务器！')
          } else if (err.response && err.response.data && err.response.data.message) {
            // if (err.response.data.message.indexOf('工单结果提交失败: 工卡已经执行完成') !== -1) {
            //   that.deleteAllWorkcardInformationWithConfirm(workcard, '工单结果提交失败, 工卡已经执行完成: ' + that.getWorkcardID(workcard) + ',是否删除移动端该工卡?')
            // } else {
            that.$message.error('工卡上传出错: ' + err)
            // }
          } else {
            that.$message.error('工卡上传出错: ' + err)
          }
          that.loading = false
        }
      )
    },
    handleSelectionChange(val) {
      this.selectedWorkcards = val
    },
    handleDelete() {
      const that = this
      if (that.selectedWorkcards.length === 0) {
        that.$message.warning('请选择需要删除的工卡！')
      }
      const workcards = this.worklist.filter(workcard => that.selectedWorkcards.find(selectedWorkcard => selectedWorkcard.workuid === workcard.workuid))
      that.deleteAllWorkcardInformationWithConfirm(workcards, '是否要删除所选择的工卡?')
    },
    deleteAllWorkcardInformationWithConfirm(workcards, confirmMessage) {
      const that = this
      that.$confirm(confirmMessage, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.deleteAllWorkcardInformation(workcards).then(
          msg => {
            that.loading = false
            that.$message({
              type: 'success',
              message: msg
            })
          },
          error => {
            that.loading = false
            that.$message({
              type: 'error',
              message: error
            })
          }
        )
      }).catch(() => {
        that.loading = false
        that.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    deleteAllWorkcardInformation(workcards) {
      const that = this
      const workcardDeletions = []
      // 根据传入的workcard删除工卡所有的信息，包括附件，照片，工卡， 以及workdatas信息
      workcards.forEach(
        workcard => {
          console.log('[upload]-[handleDelete]-workcard.workuid: ' + workcard.workuid)
          // 删除工卡所对应的附件信息
          const attachments = getAllAttachments(workcard)
          attachments.forEach(
            attachment => {
              console.log('[upload]-[handleDelete]-attachment: ' + attachment.path)
              deleteAttachment(getWorkcardID(workcard), attachment.path)
            }
          )
          // 删除工卡对应的照片
          const photoObjects = getAllPhotoObjects(workcard)
          photoObjects.forEach(
            photoObject => {
              console.log('[upload]-[handleDelete]-photo: ' + photoObject.path)
              deletePhoto(getWorkcardID(workcard), photoObject.path)
            }
          )

          // 删除工卡
          workcardDeletions.push(deleteWorkcard(workcard))
        }
      )

      return Promise.all(workcardDeletions).then(
        () => {
          // that.selectedWorkcards.splice(that.selectedWorkcards.findIndex(v => v.workuid === workcard.workuid), 1)
          console.log('[upload]-[handleDelete]-removeFromList: ')
          console.log(workcards.map(v => v.workrelattrs.find(w => w.name === 'ID').value))
          workcards.forEach(
            deletedWorkcard => {
              that.worklist.splice(that.worklist.findIndex(v => v.workuid === deletedWorkcard.workuid), 1)
              console.log('[upload]-[handleDelete]-worklist: ')
              console.log(that.worklist)
              that.workdatas.splice(that.workdatas.findIndex(v => v.workuid === deletedWorkcard.workuid), 1)
            }
          )
          return '删除成功！'
        },
        error => {
          return error
        }
      )
    },
    routeTo(workuid) {
      console.log('Route to ' + workuid)
    }
  }
}
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
